package com.linkallcloud.web.controller;

import java.net.URLEncoder;
import java.time.Duration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.linkallcloud.core.exception.BizException;
import com.linkallcloud.core.lang.Strings;
import com.linkallcloud.core.principal.Principal;
import com.linkallcloud.core.www.ISimpleUser;
import com.linkallcloud.web.utils.Controllers;

public abstract class AbstractLoginController extends AbstractLocalLoginController {

    public String loginFromSSO(String myAppCode, String myAppH5Home, String redirect, HttpServletRequest request,
            HttpServletResponse response) {
        String token = loginAndGenToken(request, myAppCode, Duration.ofMinutes(10));
        Controllers.sendLacTokenCookie(token, request, response);
        String url = myAppH5Home;
        if (!Strings.isBlank(redirect)) {
            url = url + "#" + redirect;
        }
        return Controllers.redirect(url);
    }

    public String logoutFromSSO(String myAppCode, String appServerName, String ssoServer, HttpServletRequest request,
            HttpServletResponse response) {
        ISimpleUser user = getOnlineHelper().getSessionUser(request);
        try {
            getOnlineHelper().logout(request);
            Controllers.removeLacTokenCookie(request, response);
        } catch (Exception e) {
        }

        StringBuilder sb = new StringBuilder();
        if (!appServerName.startsWith("http")) {
            sb.append(request.isSecure() ? "https://" : "http://");
        }
        sb.append(appServerName);
        sb.append(request.getContextPath());
        sb.append("/ssoauth");

        Integer clazz = parseAppClazz(user, request, response);
        if (clazz != null) {
            sb.append("?clazz=").append(clazz);
        }
        String service = sb.toString();
        try {
            service = URLEncoder.encode(service, "UTF-8");
        } catch (Exception e) {
        }
        return Controllers.redirect(ssoServer + "/logout?from=" + myAppCode + "&service=" + service
                + (clazz != null ? ("&clazz=" + clazz) : ""));
    }

    protected abstract ISimpleUser getUserByLoginName(int appClazz, String loginName);

    protected ISimpleUser getSessionUserByPrincipal(Principal ssoPrincipal) throws BizException {
        if (ssoPrincipal != null) {
            String loginName = Controllers.getLoginNameByPrincipal(ssoPrincipal);
            ISimpleUser user = getUserByLoginName(ssoPrincipal.getSiteClazz(), loginName);
            if (user != null) {
                return user;
            }
        }
        throw new BizException("e.login", "根据ssoPrincipal加载用户Dto，并转化成SessionUser发生错误");
    }

    protected String loginAndGenToken(HttpServletRequest request, String appCode, Duration timeout) {
        // 若有sso, 并且sso未超时, principal为sso验证后的用户帐号
        Principal principal = Controllers.getSSOPrincipal(appCode, request);
        if (principal != null) {// SSO认证，且已经通过SSO认证，但是本地未登陆
            ISimpleUser psu = getSessionUserByPrincipal(principal);
            if (psu != null) {
                return getOnlineHelper().login(psu, timeout);
            }
        }
        throw new BizException("e.login", "登陆失败");
    }

    // protected String loginAndGenRedirectUrlWithToken(HttpServletRequest request, String appCode, String h5Home,
    // String redirect, Duration timeout) {
    // String token = loginAndGenToken(request, appCode, timeout);
    // try {
    // String h5Url = h5Home;
    // if (!Strings.isBlank(redirect)) {
    // if (redirect.startsWith("http")) {
    // h5Url = redirect;
    // } else {
    // h5Url += redirect;
    // }
    // }
    //
    // String childPath = "";
    // int idx = h5Url.indexOf("#");
    // if (idx != -1) {
    // childPath = h5Url.substring(idx);
    // h5Url = h5Url.substring(0, idx);
    // }
    //
    // UrlPattern up = new UrlPattern(h5Url).append(Controllers.TOKEN_PARAM_NAME, token);
    // return up.url() + childPath;
    // } catch (Throwable e) {
    // log.error(e.getMessage(), e);
    // }
    // throw new BizException("e.login", "登陆失败");
    // }

}
